package com.javalab.springmvc.servlet;

import java.io.IOException;
import java.util.Arrays;
import java.util.Enumeration;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.FrameworkServlet;

import com.javalab.springmvc.controller.HelloController;

/**
 * Servlet implementation class TestWebAppContext
 */
@WebServlet("/TestWebAppContext")
public class TestWebAppContext extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public TestWebAppContext() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		ServletContext servletContext = request.getServletContext();

		Enumeration<String> attributeNames = servletContext.getAttributeNames();
		while (attributeNames.hasMoreElements()) {
			System.out.println(attributeNames.nextElement());
		}

		WebApplicationContext wac = (WebApplicationContext) servletContext
				.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
		System.out.println(Arrays.toString(wac.getBeanDefinitionNames()));

		System.out.println(wac.getBean(HelloController.class));

		WebApplicationContext wac2 = (WebApplicationContext) servletContext
				.getAttribute(FrameworkServlet.SERVLET_CONTEXT_PREFIX
						+ "mvc-dispatcher");

		System.out.println(Arrays.toString(wac2.getBeanDefinitionNames()));
		System.out.println(wac2.getBean(HelloController.class));
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
